<?php
namespace Framework\Library\Core;

/**
 * 应用程序类
 */
class Application{
	
	public $name;
	public $path;
	public $config;
	public $request;
	public $module;
	
	/**
	 * 如果当前应用是被其他应用程序纵向调用的，那么这个属性指向父应用程序对象，否则为NULL
	 * @var Application
	 */
	public $parent;
	
	function __construct($path,$request=NULL,$parent = NULL){
		
		$this->initApplicationName($path);
		
		$this->path = $path;
		
		require_once 'Config.class.php';
		$this->config = new Config($path.'/Config.php');
		
		require_once 'Request.class.php';
		if (!empty($request)) $this->request = $request;
		else $this->request = new Request();
		
		if (empty($this->request->module)) $this->request->module = $this->config ->DefaultModule;
		
		$this->parent = $parent;
		
		date_default_timezone_set($this->config ->Timezone);
		
	}
	
	/**
	 * 从应用程序路径提取应用程序名
	 * @param unknown_type $path
	 */
	private function initApplicationName($path){
		$info = pathinfo(realpath($path));
		$this ->name = $info['basename'];
	}

	/**
	 * 运行应用程序
	 *
	 * @return void
	 */
	public function run(){
	
		$module = $this ->request ->module.'Module';
	
		require_once 'Module.class.php';
		
		// 检查应用程序模块是否存在
		$module_file = $this ->path.'/Module/'.$module.'.class.php';
		
		if (!file_exists($module_file)){
			header('HTTP/1.1 404 Not Found');
			throw new \Exception('错误的请求，找不到应用程序模块：'.$this ->request ->module.'。');
		}
		
		// 实例化应用程序模块，并执行操作
		require_once $this ->path.'/Module/'.$module.'.class.php';
		
		$fullModuleName = 'Application\\'.$this ->name.'\Module\\'.$module;
		$this ->module = new $fullModuleName($this);
		
		if (empty($this ->request ->action))$action = $this ->request ->action = $this ->module ->defaultAction;
		else $action = $this ->request ->action;
		$this ->module ->$action();
	
	}
	
}